<template>
	<div class="div1">
		<template v-if="showObj == null">
			<el-skeleton :rows="5" animated />
			<el-text type="info">点击按钮查看邮件...</el-text>
		</template>
		<template v-else>
			<el-descriptions column="3">
				<template #title>
					<h3>
						邮件详情:
					</h3>
					<el-text type="success" v-html="getMessage(showObj, false)"></el-text>
				</template>
				<el-descriptions-item span="3">
					<div class="messagestyle">
						{{ showObj.message }}
					</div>
				</el-descriptions-item>
				<el-descriptions-item align="right" span="3" label="备注:" v-if="showObj.notes">
					{{ showObj.notes }}
				</el-descriptions-item>
				<el-descriptions-item align="right">
					<!-- 根据按钮组的类型，然后选择性的展示按钮 -->
					<div v-if="showObj.sendType === 'FQUERY'">
						<template v-if="showObj.result == 'wait'">
							<el-button-group>
								<loadBtn buttonType="success" @click="addFriend(showObj._id, 'ok')">
									<template #default>
										同意申请
									</template>
								</loadBtn>
								<loadBtn buttonType="warning" @click="addFriend(showObj._id, 'no')">
									<template #default>
										拒绝申请
									</template>
								</loadBtn>
							</el-button-group>
						</template>
						<template v-else-if="showObj.result == 'no'">
							<el-text type="danger">请求已拒绝</el-text>
						</template>
						<template v-else-if="showObj.result == 'ok'">
							<el-text type="success">请求已接受</el-text>
						</template>
					</div>
					<div v-else-if="showObj.sendType === 'HINT'">
						<template v-if="emailData.readBoolean(showObj._id)">
							<el-button type="primary" @click="setEmailRead(showObj._id)">
								<el-icon>
									<Checked />
								</el-icon>
								设置已读
							</el-button>
						</template>
						<template v-else>
							<el-button type="danger" @click="deleteEmail(showObj._id)">
								<el-icon>
									<DocumentDelete />
								</el-icon>
								删除已读邮件
							</el-button>
						</template>
					</div>
					<div v-else>普通消息</div>
				</el-descriptions-item>
			</el-descriptions>
		</template>
	</div>
	<div class="div2">
		<el-timeline>
			<template v-for="(unit, index) in emailData.getemailList" :key="index">
				<!-- 申请类型 -->
				<el-timeline-item v-if="unit.sendType == 'FQUERY'" color="#44cccc" :timestamp="getTime(unit.time)"
					placement="top">
					<el-text type="info" v-html="getMessage(unit)"></el-text><br>
					<el-card style="width: 80%;">
						<template #header>
							<div class="FQUERY-Header">
								<div class="FQUERY-div1">
									<el-avatar shape="square" size="small" :src="unit.meta.avatarPath" />
								</div>
								<div class="FQUERY-div2">
									<el-text type="info" size="small">{{ unit.notes }}</el-text>
								</div>
							</div>
						</template>
						<el-text truncated>备注:{{ unit.message }}</el-text>
						<template #footer>
							<el-button-group>
								<el-button type="success" @click="changeShow(unit)">
									<el-icon>
										<List />
									</el-icon>
									详情
								</el-button>
								<el-button type="primary" @click="setEmailRead(unit._id)">
									<el-icon>
										<Checked />
									</el-icon>
									已读
								</el-button>
								<el-button type="danger" @click="deleteEmail(unit._id)">
									<el-icon>
										<DocumentDelete />
									</el-icon>
									删除
								</el-button>
							</el-button-group>
						</template>
					</el-card>
				</el-timeline-item>
				<!-- 当用户离线的时候，有其他用户发送信息（私聊）时，保存为邮件 -->
				<el-timeline-item v-else-if="unit.sendType == 'PC'" @mouseenter="setEmailRead(unit._id)" color="#59b385"
					:timestamp="getTime(unit.time)" placement="top">
					<el-text type="info" v-html="getMessage(unit)"></el-text><br>
					{{ unit.message }}
				</el-timeline-item>
				<!-- 提示类型，通常是用来提示用户回调的结果 -->
				<el-timeline-item v-else-if="unit.sendType == 'HINT'"
					:color="unit.result == 'ok' ? '#59b385' : '#ff0000'" :timestamp="getTime(unit.time)"
					placement="top">
					<el-text type="info" v-html="getMessage(unit)"></el-text><br>
					<el-card style="width: 80%;">
						<p>{{ unit.notes }}</p>
						<el-text truncated>备注:{{ unit.message }}</el-text>
						<template #footer>
							<el-button-group>
								<el-button type="success" @click="changeShow(unit)">
									<el-icon>
										<List />
									</el-icon>
									详情
								</el-button>
								<el-button type="primary" @click="setEmailRead(unit._id)">
									<el-icon>
										<Checked />
									</el-icon>
									已读
								</el-button>
								<el-button type="danger" @click="deleteEmail(unit._id)">
									<el-icon>
										<DocumentDelete />
									</el-icon>
									删除
								</el-button>
							</el-button-group>
						</template>
					</el-card>
				</el-timeline-item>
			</template>
			<template v-if="emailData.getemailList.length == 0">
				<el-empty>
					<el-text type="info">数据不存在.....</el-text>
				</el-empty>
			</template>
		</el-timeline>
	</div>
	<div class="div3">
		<!-- 过滤邮件组件 -->
		<EmailFilter></EmailFilter>
	</div>
	<div class="div4">
		<div class="vertical-line"></div>
	</div>
	<div class="div5">
		<div class="vertical-divider"></div>
	</div>
</template>

<script setup>
import {
	ref,
	getCurrentInstance,
	reactive,
	computed
} from 'vue';

import {
	ElNotification
} from 'element-plus'

import loadBtn from "@/element/loadBtn.vue"
import EmailFilter from "./EmailFilter.vue"

let {
	proxy
} = getCurrentInstance();


import useEmail from "@/store/email.js"
import useUser from "@/store/user.js"
import useFriend from "@/store/friend.js"
let emailData = useEmail();
let userData = useUser();
let FriendData = useFriend();

proxy.$axios.post("/email/getEmails").then((rls) => {
	if (rls.data.result) {
		emailData.updateEmailData(rls.data.data.emails);
		emailData.updateReadData(rls.data.data.readList);
	} else {
		emailData.updateEmailData([]);
		ElNotification({
			title: '错误!',
			message: '错误，邮件列表获取失败！',
			type: 'error',
			offset: 100,
			duration: 3000,
		})
	}
}).catch((error) => {
	ElNotification({
		title: '错误!',
		message: '用户登录失败，请检查网络连接！',
		type: 'error',
		offset: 100,
		duration: 3000,
	})
});



// 向后端发送回执的方法
let addFriend = (emilId, select) => {
	proxy.$axios.post("/friend/addFriend", {
		emilId,
		select
	}).then((rls) => {
		if (rls.data.result) {
			if (select == "no") {
				ElNotification({
					title: '已拒绝好友请求！',
					message: "该用户的好友申请已被拒绝",
					type: 'success',
					offset: 100,
					duration: 3000,
				})
			} else if (select == "ok") {
				// 刷新好友列表
				FriendData.renewData(proxy.$axios, userData.user.friendId);
				// 提示添加成功
				ElNotification({
					title: '好友添加成功！',
					message: "快去和他聊聊吧！",
					type: 'success',
					offset: 100,
					duration: 3000,
				})
			}
			// 设置邮件和结果值
			emailData.setEmailResult(emilId, select);
		} else {
			ElNotification({
				title: '添加错误!',
				message: rls.data.data,
				type: 'error',
				offset: 100,
				duration: 3000,
			})
		}
	}).catch((error) => {
		ElNotification({
			title: '错误!',
			message: '用户请求失败，请检查网络连接！',
			type: 'error',
			offset: 100,
			duration: 3000,
		})
	});
}


// 设置邮件的已读状态的方法
let setEmailRead = (emailId, flag = true) => {
	emailData.setRead(emailId, flag);
}

// 删除邮件的方法
let deleteEmail = (emailId) => {
	emailData.deleteEmail(emailId);
}


// 当用户点击的时候，修改显示值
let showObj = ref(null);
let changeShow = (unit) => {
	showObj.value = unit;
	let id = unit.sendID == userData.user._id ? unit.receiveID : unit.sendID;
	let messageObj = FriendData.findIndexById(id);
	showObj.value.sendName = (messageObj.remark || messageObj.username || id)
}



// 格式化时间信息的方法
let getTime = (time) => {
	let timeObj = new Date(time);
	return timeObj.toLocaleString();
}

// 格式化信息来源的方法
let getMessage = (unit, select = true) => {
	let messageText = "";
	let id = unit.sendID == userData.user._id ? unit.receiveID : unit.sendID;
	let messageObj = FriendData.findIndexById(id);

	// 对比该邮件是发送还是接收    
	if (unit.sendID == userData.user._id) {
		messageText = "你 致 " + (messageObj.remark || messageObj.username || unit.room || id);
	} else {
		messageText = (messageObj.remark || messageObj.username || unit.meta.addName || id) + " 致 你";
	}

	// 使用HTML和CSS的flex布局来控制文本的对齐方式    
	let readStatusSpan = "";

	if (select) {
		if (emailData.readBoolean(unit._id)) {
			readStatusSpan = `<b class='readTrue'>已读</b>`;
		} else {
			readStatusSpan = `<b class='readFalse'>未读</b>`;
		}
	}

	messageText = `<div style="display: flex; justify-content: space-between; align-items: center;">    
	        <span style="text-align: left;">${messageText}</span>    
	        ${readStatusSpan}    
	    </div>`;

	return messageText;
}
</script>

<style scoped>
.div1 {
	grid-area: 1 / 1 / 20 / 16;
}

.div2 {
	grid-area: 1 / 16 / 20 / 31;
	overflow: auto;
}

.div3 {
	grid-area: 22 / 1 / 31 / 31;
}

.div4 {
	grid-area: 21 / 1 / 22 / 31;
}

.div5 {
	grid-area: 1 / 16 / 20 / 17;
}

.EmailUnit {
	width: 80%;
	height: 120px;
	margin: 10px auto;
	border: 2px solid rgba(201, 201, 201, 0.6);
}

.FQUERY-Header {
	display: grid;
	grid-template-columns: repeat(8, 1fr);
	grid-template-rows: repeat(3, 1fr);
	grid-column-gap: 0px;
	grid-row-gap: 0px;

	width: 100%;
	height: 30px;
}

.FQUERY-div1 {
	grid-area: 1 / 1 / 2 / 4;
}

.FQUERY-div2 {
	grid-area: 1 / 2 / 4 / 9;
}

/* 这里的样式如果想要应用，需要将样式穿透处理 */
::v-deep .readTrue {
	color: #00cd00;
	margin-right: 2em;
}

::v-deep .readFalse {
	color: #f50000;
	margin-right: 2em;
}

::v-deep .messagestyle {
	max-width: 300px;
	height: 5em;
	text-indent: 2em;
	word-break: break-all;
	margin: 10px auto;
}

.data-unit-card {
	margin: 20px;
	padding: 20px;
	box-sizing: border-box;
	border-radius: 4px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.vertical-divider {
	width: 2px;
	height: 100%;
	background-color: transparent;
	border-left: 2px solid rgba(201, 201, 201, 0.6);
	margin: 0 10px;
	display: inline-block;
	vertical-align: middle;
}

.vertical-line {
	width: 100%;
	height: 2px;
	background-color: transparent;
	border-top: 2px solid rgba(201, 201, 201, 0.6);
	margin: 10 0px;
	display: inline-block;
	vertical-align: middle;
}
</style>